package src.helpers;

public class Barrier {

	Semaphore mutex;
	int sleepers;
	int maxSleepers;

	public Barrier(int maxSleepers) {

		this.sleepers = 0;
		this.maxSleepers = maxSleepers;
		mutex = new Semaphore(1);

	}

	public synchronized void block() throws InterruptedException {
		mutex.down();
		sleepers++;
		if (sleepers == maxSleepers) {
			this.releaseAll();
			mutex.up();
		} else {
			mutex.up();
			wait();
		}
	}

	public synchronized void release() throws InterruptedException {
		notify();
	}

	public synchronized void releaseAll() throws InterruptedException {
		System.out.println(" is now releasing all from the block.");
		sleepers = 0;
		notifyAll();
	}

}